package com.thoughtworks.util.http;

import java.io.IOException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.log4j.Logger;

public class PutRequestExecutor implements RequestExecutor {
    private static final Logger logger = Logger.getLogger(PutRequestExecutor.class);

    private HttpClient httpClient;
    private PutMethod putMethod;

    public PutRequestExecutor(HttpClient httpClient, PutMethod putMethod) {
        this.httpClient = httpClient;
        this.putMethod = putMethod;
    }

    public void execute(Object requestData, HttpResponseHandler handler) {
        final String requestString = (String) requestData;
        putMethod.setQueryString(EncodingUtil.getString(requestString.getBytes(), "UTF-8"));
        
        try {
            int responseCode = httpClient.executeMethod(putMethod);
            Header[] headers = putMethod.getRequestHeaders();

            handler.handle(responseCode, AndrosphereUtils.convertToMap(headers), putMethod.getResponseBodyAsStream());
        } catch (IOException e) {
            String message = "Error executing PUT request to URL: " + getUrl();
            logger.error(message, e);
            throw new HttpTemplateException(message, e);
        } finally {
            putMethod.releaseConnection();
        }
    }

    public void setRequestHeader(String headerName, String headerValue) {
        putMethod.setRequestHeader(headerName, headerValue);
    }

    public String getUrl() {
        try {
            return putMethod.getURI().toString();
        } catch (URIException e) {
            e.printStackTrace();
        }
        return null;
    }
}
